import { ApiMeta } from '@components/ApiMeta.tsx';

# VirtualModulesPlugin

<ApiMeta specific={['Rspack']} addedVersion="1.5.0" />

`VirtualModulesPlugin` allows you to create, modify, and delete files in memory, and Rspack treats these virtual files as if they were real files existing in the file system.

This plugin is a Rust implementation of [webpack-virtual-modules](https://github.com/sysgears/webpack-virtual-modules), deeply integrated with Rspack to provide equivalent functionality with better performance.

## Usage

### Basic usage

When creating a `VirtualModulesPlugin` instance, you can directly configure virtual modules in the constructor:

```ts
import { rspack } from '@rspack/core';

new rspack.experiments.VirtualModulesPlugin({
  // ...modules
});
```

- **Parameters:**
  - `modules` (optional): An object where keys are file paths and values are file contents.

```js title="rspack.config.mjs"
import { rspack } from '@rspack/core';

export default {
  plugins: [
    new rspack.experiments.VirtualModulesPlugin({
      'src/generated/config.js': 'export default { version: "1.0.0" };',
      'src/generated/constants.js': `
        export const API_URL = "${process.env.API_URL || 'http://localhost:3000'}";
        export const DEBUG = ${process.env.NODE_ENV !== 'production'};
      `,
    }),
  ],
};
```

### Dynamic module creation

You can dynamically create or modify virtual modules using the `writeModule` method.

:::note
Because the plugin's virtual modules are managed on the Rust side,
the `writeModule` method becomes available only after the Rust compiler has been initialized.
For example, invoking `writeModule` within the `beforeCompile` or `compile` hooks
will throw the following error: `Error: Virtual file store has not been initialized.`
:::

- **Type:**

```ts
function writeModule(filePath: string, contents: string): void;
```

- **Parameters:**
  - `filePath`: The virtual file path relative to [compiler.context](/api/javascript-api/compiler#context)
  - `contents`: The content of the virtual file

- **Example:**

```js title="rspack.config.mjs"
import { rspack } from '@rspack/core';

const virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin();

export default {
  plugins: [
    virtualModulesPlugin,
    {
      apply(compiler) {
        compiler.hooks.thisCompilation.tap('MyPlugin', () => {
          // Dynamically create virtual modules
          const moduleContent = generateSomeContent();
          virtualModulesPlugin.writeModule('src/dynamic.js', moduleContent);
        });
      },
    },
  ],
};
```
